package com.neuedu.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.myUtil.JwtUtil;
import com.neuedu.pojo.User;
import com.neuedu.service.IUserService;
import com.neuedu.util.CommonResult;
import com.neuedu.util.ShaUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
public class LoginController {
	@Resource

	private IUserService userService;
	@PostMapping("/login")
	public CommonResult login(@RequestBody Map<String,Object> param){
		System.out.println(param);
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		wrapper.eq("telephone", param.get("telephone")).eq("password", ShaUtil.getSHA256(param.get("password").toString()));
		User user =  userService.getOne(wrapper);
		if (user == null){
			return CommonResult.failed("手机号或密码错误");
		}
		user.setLastLogin(LocalDateTime.now());
		updateLoginTime(user.getId());
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("token", JwtUtil.create(user));
		jsonObject.put("id",user.getId());
		return CommonResult.success(jsonObject);
	}

	private void updateLoginTime(int id){
		User user = new User();
		user.setId(id);
		user.setLastLogin(LocalDateTime.now());
		userService.updateById(user);
	}
}